package data.join.com.service;

import android.app.Service;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;

import data.join.com.utils.MyLog;


/**
 * Created by Administrator on 2017/7/26.
 */

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class JobSchedulerService extends JobService {
    private static final int JOB_ID = 1001;

    private String TAG = JobSchedulerService.class.getSimpleName();

    JobScheduler jobScheduler;

    @Override
    public void onCreate() {
        super.onCreate();

        MyLog.D(TAG,"onCreate");

        jobScheduler = (JobScheduler)getSystemService(Context.JOB_SCHEDULER_SERVICE);

        startJobScheduler();
    }

    @Override
    public int onStartCommand(Intent intent,int flags, int startId) {
        return Service.START_STICKY;
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        //MyLog.D(TAG,"onStartJob");
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        //MyLog.D(TAG,"onStopJob");
        return false;
    }

    private void startJobScheduler(){
        try {
            jobScheduler.cancel(JOB_ID);

            JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, new ComponentName(getPackageName(), JobSchedulerService.class.getName()));
            builder.setPeriodic(60*1000);
            builder.setPersisted(true);

            if( jobScheduler.schedule( builder.build() ) == JobScheduler.RESULT_SUCCESS ) {
                MyLog.D(TAG,"startJobScheduler success.");
            }else{
                MyLog.D(TAG,"startJobScheduler fail.");
            }
        }catch (Exception e){
            MyLog.D(TAG,"startJobScheduler Exception.");
            e.printStackTrace();
        }

    }
}
